<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件


/**
 * 数组去重
 * @param $arr
 * @return mixed
 */
function array_filter_full($arr){
    foreach($arr as $key=>$value){
        if($value ===''){
            unset($arr[$key]);
        }
    }
    return $arr;
}
/**
 * 生成username账号
 */
function createUsername(){
    //打开锁文件
    $fp = fopen('./public/lock/create_username.lock','r');
    flock($fp,LOCK_SH);
    $str = getCode(2,3);//小写字母字符串(两位)
    $str .= msectime();//毫秒时间戳
    //关闭锁
    flock($fp,LOCK_UN);
    fclose($fp);
    return $str;
}
/**
 * 获取毫秒时间戳
 */
function msectime() {
    list($msec, $sec) = explode(' ', microtime());
    $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}

/**
 * 生成默认密码123456
 * @param string $username
 * @return ['encrypt','password'] 加密字段跟md5密码
 */
function createPwd($username=''){
    if(!empty($username)){
        $username = strval($username);
        $pwd = '123456';
        $encrypt = getCode(6,3);
        return ['encrypt'=>$encrypt,'password'=>getMd5($pwd,$username,$encrypt)];
    }else{
        return false;
    }
}

/**
 * 随机产生安全码
 * @param $len int 长度
 * @param $type int 类型 1全部字母数字  2数字  3小写字母  4大写字母
 * @return string
 */
function getCode($len,$type=1){
    $code = '';
    switch($type){
        case 1:
            $str = 'abcdefghijklmnopqrstuvwxyz0123456789';
            break;
        case 2:
            $str = '0123456789';
            break;
        case 3:
            $str = 'abcdefghijklmnopqrstuvwxyz';
            break;
        case 4:
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
        case 5:
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            break;
        default:
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    }
    for($i=0;$i<$len;$i++){
        $code .= $str[mt_rand(0,mb_strlen($str,'utf-8') -1 )] ;
    }
    return $code;
}

/**
 * 密码加密算法
 * @time 2017/11/16
 * @param string $pwd 明文密码
 * @param string $username 用户名
 * @param string $encrypt 随机安全码
 * @return string 32位加密字符串
 */
function getMd5($pwd,$username,$encrypt){
    $username = strtolower($username);
    return md5(md5($pwd).$username.$encrypt);
}

/**
 * 获取真实IP
 * @return array|false|string
 */
function get_ip() {
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
    else
        if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else
            if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
                $ip = getenv("REMOTE_ADDR");
            else
                if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
                    $ip = $_SERVER['REMOTE_ADDR'];
                else
                    $ip = "unknown";
    return ($ip);
}

/**
 * 获取文件扩展名
 * @param string $file 文件路径
 * @return string txt/jpg
 * */
function getExtension($file=''){
    if($file){
        return pathinfo($file, PATHINFO_EXTENSION);
    }
}


/**
 * 转换单位 支持 TB/GB/MB/KB/B  不限大小写 转换为字节
 * @param string $size 文件大小 例：100MB
 * @return int 1024000
 */
function tfFilesize($size=''){
    if(empty($size)){
        return 0;
    }

    //1、获取大小数值
    $sizenum = floatval($size);
    if(empty($sizenum)){
        return 0;
    }

    //2、根据大小数值获取后面单位
    $cm = explode($sizenum,$size);
    $cm = !empty($cm[1])?strtolower(trim($cm[1])):'';
    $res = 0;
    $base= 1024;
    switch ($cm){
        case 'tb':
            $res = $sizenum*$base*$base*$base*$base;
            break;
        case 'gb':
            $res = $sizenum*$base*$base*$base;
            break;
        case 'mb':
            $res = $sizenum*$base*$base;
            break;
        case 'kb':
            $res = $sizenum*$base;
            break;
        case 'b':
            $res = $sizenum;
            break;
        default:
            break;
    }

    return ceil($res);
}

/**
 * 权限递归循环取得无限分级
 * @param $arr 处理数组
 * @param int $pid 父级键
 * @return array 返回
 */
function grade($arr,$pid=0){
    $pgrade = array();//定义一个空数组
    foreach ($arr as $item) {//遍历输出数组内容
        if ($item['pid'] == $pid) {//父id与内容ID相同
            $item['children'] = grade($arr, $item['id']);//继续调用本身
            if (empty($item['children'])) {//如果子内容为空，
                unset($item['children']);//销毁指定的变量
            }
            $pgrade[] = $item;//否则输出$item内容
        }
    }
    return $pgrade;//循环结束，返回数组内容
}

/**
 * 根据日期转换英文，返回 05 Jan 2018 （日 月 年）
 * @param date 日期，格式：2018-05-05
 */
function dmy($dates=''){
    $day = '';
    $moth = '';
    $year = '';
    if(!empty($dates)){
        $day = date('d',strtotime($dates));
        $moth = date('m',strtotime($dates));
        $moth_arr = [
            '01'=>'Jan','02'=>'Feb','03'=>'Mar','04'=>'Apr','05'=>'May','06'=>'Jun',
            '07'=>'Jul','08'=>'Aug','09'=>'Sept','10'=>'Oct','11'=>'Nov','12'=>'Dec'
        ];
        $moth = isset($moth_arr[$moth])?$moth_arr[$moth]:'';
        $year = date('Y',strtotime($dates));
    }
    return $day.' '.$moth.' '.$year;
}

/**
 * 根据日期，拆分成日 月，并组成一个数组
 * @param string $dates
 */
function dm($dates=''){
    $day = '';
    $moth = '';
    if(!empty($dates)) {
        $day = date('d', strtotime($dates));
        $moth = date('m',strtotime($dates));
        $moth_arr = [
            '01'=>'Jan','02'=>'Feb','03'=>'Mar','04'=>'Apr','05'=>'May','06'=>'Jun',
            '07'=>'Jul','08'=>'Aug','09'=>'Sept','10'=>'Oct','11'=>'Nov','12'=>'Dec'
        ];
        $moth = isset($moth_arr[$moth])?$moth_arr[$moth]:'';
    }
    $dm =[
        'day'=>$day,
        'moth'=>$moth
    ];
    return $dm;
}

/**
 * 截取文章内容的前100个字节
 * @param $content
 */
function short_content($content){
    $content=str_replace(" ","",$content);
    $contents = preg_replace("/<[^>]+>/", '', $content);
    $res = substr($contents,0,100);//截取字节
    return $res.'.....';
}

/**
 * 系统邮件发送函数
 * @param string $to 接收邮件者邮箱
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 */
function SendMail($title,$username,$time,$email,$url)
{
    $config = config('email');
    import('org.util.phpmailer.PHPMailer');
    $mail = new \PHPMailer;
    $mail->CharSet = 'utf-8';//设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码，
    $mail->IsSMTP();//设定使用SMTP服务
    $mail->SMTPSecure = 'ssl';
    $mail->SMTPDebug = 1;//关闭SMTP调试功能//1=errors and messages//2=messages only
    $mail->SMTPAuth  = true;//启用SMTP验证功能
    $mail->Port      = $config['mail_port'];  // SMTP服务器的端口号
    $mail->Host      = $config['mail_smtp'];
    $mail->AddAddress($email);//添加收件人地址，
    $mail->Body      = "亲爱的" . $username . "：<br/>您在" . $time . "提交了通过邮箱".$email."找回密码请求。请点击下面的链接重置密码（按钮24小时内有效）。<br/><a href='" . $url . "' target='_blank'>" . $url . "</a><br/>如果以上链接无法点击，请将它复制到你的浏览器地址栏中进入访问。<br/>如果您没有提交找回密码请求，请忽略此邮件。"; //设置邮件正文
    $mail->From      = $config['mail_address'];//设置发件人名字
    $mail->FromName  = '管理员团队';//设置发件人名字
    $mail->Subject   = $title;//设置邮件标题
    $mail->Username  = $config['mail_loginname'];//设置用户名和密码
    $mail->Password  = $config['mail_password'];
    return($mail->Send());
}